<template>
  <view class="job-list-container">
    <!-- 搜索栏 -->
    <view class="search-bar">
      <uni-search-bar 
        placeholder="搜索兼职名称" 
        radius="100" 
        clearButton="auto"
        cancelButton="none"
        @confirm="handleSearch"
        v-model="searchKeyword"
      />
    </view>
    
    <!-- 分类筛选 -->
	<u-tabs @change="changeCategory" :list="categories"></u-tabs>
    <!-- 排序选项 -->
    <view class="sort-options">
      <view 
        class="sort-item"
        :class="{active: sortType === 'default'}"
        @click="changeSort('default')"
      >
        <text>默认</text>
      </view>
      <view 
        class="sort-item"
        :class="{active: sortType === 'time'}"
        @click="changeSort('time')"
      >
        <text>最新</text>
        <uni-icons 
          :type="timeSortOrder === 'asc' ? 'arrowup' : 'arrowdown'" 
          size="14" 
          color="#999"
          v-if="sortType === 'time'"
        />
      </view>
      <view 
        class="sort-item"
        :class="{active: sortType === 'salary'}"
        @click="changeSort('salary')"
      >
        <text>薪资</text>
        <uni-icons 
          :type="salarySortOrder === 'asc' ? 'arrowup' : 'arrowdown'" 
          size="14" 
          color="#999"
          v-if="sortType === 'salary'"
        />
      </view>
    </view>
    
    <!-- 兼职列表 -->
    <view class="job-list">
      <view 
        class="job-item" 
        v-for="item in jobList" 
        :key="item.id"
        @click="navigateToDetail(item.id)"
      >
        <view class="job-header">
          <view class="job-title">{{item.title}}</view>
          <view class="job-salary">{{item.salary}}{{item.salary_unit}}</view>
        </view>
        
        <view class="job-info">
          <view class="info-item">
            <uni-icons type="location" size="16" color="#999"></uni-icons>
            <text>{{item.location}}</text>
          </view>
          <view class="info-item">
            <uni-icons type="calendar" size="16" color="#999"></uni-icons>
            <text>{{item.start_time}}</text>
          </view>
        </view>
        
        <view class="job-footer">
          <view class="company-info">
            <image class="company-logo" :src="item.logo" mode="aspectFill"></image>
            <text class="company-name">{{item.name}}</text>
          </view>
          <view class="publish-time">{{formatRelativeTime(item.created_at)}}</view>
        </view>
        
     <!--   <view class="job-tags">
          <view class="tag" v-if="item.isSchool">校内</view>
          <view class="tag" v-if="item.isUrgent">急招</view>
          <view class="tag" v-if="item.isVerified">认证</view>
        </view> -->
      </view>
      
      <!-- 加载更多 -->
      <view class="load-more" v-if="hasMore">
        <text>{{loading ? '加载中...' : '上拉加载更多'}}</text>
      </view>
      <view class="no-more" v-else>
        <text>没有更多了~</text>
      </view>
    </view>
    
  
  </view>
</template>

<script>
export default {
  data() {
    return {
      searchKeyword: '',
      currentCategory: '',
      categories: [],
      sortType: 'default',
      timeSortOrder: 'desc',
      salarySortOrder: 'desc',
      jobList: [],
      page: 1,
      pageSize: 10,
      hasMore: true,
      loading: false,
	  jobType:'',
	  status:''
    }
  },
  onLoad() {
	  this.getJobcategories()
	this.getJobList()
  },
  onReachBottom() {
    if (this.hasMore && !this.loading) {
      this.page++;
      this.getJobList();
    }
  },
  methods: {
	async getJobcategories(){
		const res = await this.$api.get('/job/categories','',true)
		if(res.data.code === 200) {
			this.categories = res.data.data
			this.categories.unshift({
				name:'全部',
				value:'',
				id:''
			})
		}
	},
	async getJobList(){
		this.loading = true;
		const params = {
			page:this.page,
			limit:this.pageSize,
			status:this.status,
			job_type:this.jobType,
			searchKeyword:this.searchKeyword,
			sortType:this.sortType
		}
		const res = await this.$api.get('/Job/index',params,true)
		if(res.data.code === 200) {
			console.log('sssssss',res)
			this.jobList = res.data.data
			this.loading = false;
			if (this.page === 1) {
			  this.jobList = res.data.data;
			} else {
			  this.jobList = [...this.jobList, ...res.data.datas];
			}
			
			// 模拟没有更多数据的情况
			if (this.page >= 3) {
			  this.hasMore = false;
			}
		}
	},
	formatRelativeTime(dateString) {
		const date = new Date(dateString);
		const now = new Date();
		const diffInSeconds = Math.floor((now - date) / 1000);
	
		const seconds = Math.abs(diffInSeconds);
		const minutes = Math.floor(seconds / 60);
		const hours = Math.floor(minutes / 60);
		const days = Math.floor(hours / 24);
	
		if (diffInSeconds < 0) {
			// 未来时间
			if (seconds < 60) return '刚刚';
			if (minutes < 60) return `${minutes}分钟后`;
			if (hours < 24) return `${hours}小时后`;
			return `${days}天后`;
		} else {
			// 过去时间
			if (seconds < 60) return '刚刚';
			if (minutes < 60) return `${minutes}分钟前`;
			if (hours < 24) return `${hours}小时前`;
			return `${days}天前`;
		}
	},
    // 加载兼职列表
    async loadJobList() {
      this.loading = true;
      
      try {
        // 模拟API请求
        const mockData = this.getMockData();
        
        if (this.page === 1) {
          this.jobList = mockData;
        } else {
          this.jobList = [...this.jobList, ...mockData];
        }
        
        // 模拟没有更多数据的情况
        if (this.page >= 3) {
          this.hasMore = false;
        }
      } catch (error) {
        console.error('加载兼职列表失败:', error);
        uni.showToast({
          title: '加载失败',
          icon: 'none'
        });
      } finally {
        this.loading = false;
      }
    },
    
    // 获取模拟数据
    getMockData() {
      const categories = ['tutor', 'promotion', 'waiter', 'distribute', 'intern', 'other'];
      const salaryUnits = ['小时', '天', '周', '月'];
      const companies = [
        {name: '新东方教育', logo: '/static/logo/company1.jpg'},
        {name: '星巴克咖啡', logo: '/static/logo/company2.jpg'},
        {name: '肯德基', logo: '/static/logo/company3.jpg'},
        {name: '优衣库', logo: '/static/logo/company4.jpg'},
        {name: '校园快递站', logo: '/static/logo/company5.jpg'}
      ];
      
      return Array.from({length: this.pageSize}, (_, i) => {
        const randomCategory = categories[Math.floor(Math.random() * categories.length)];
        const randomCompany = companies[Math.floor(Math.random() * companies.length)];
        const salary = Math.floor(Math.random() * 100) + 50;
        const salaryUnit = salaryUnits[Math.floor(Math.random() * salaryUnits.length)];
        
        return {
          id: `job-${this.page}-${i}`,
          title: `${this.getCategoryName(randomCategory)}兼职${i + 1}`,
          category: randomCategory,
          salary: salary,
          salaryUnit: salaryUnit,
          location: `${['东区', '西区', '南区', '北区'][Math.floor(Math.random() * 4)]}${Math.floor(Math.random() * 10) + 1}号楼`,
          workTime: `${Math.floor(Math.random() * 7) + 1}天/周，${Math.floor(Math.random() * 8) + 4}小时/天`,
          companyName: randomCompany.name,
          companyLogo: randomCompany.logo,
          publishTime: `${Math.floor(Math.random() * 24) + 1}小时前`,
          isSchool: Math.random() > 0.5,
          isUrgent: Math.random() > 0.7,
          isVerified: Math.random() > 0.8
        };
      });
    },
    
    // 获取分类名称
    getCategoryName(value) {
      const category = this.categories.find(item => item.value === value);
      return category ? category.name : '其他';
    },
    
    // 搜索
    handleSearch() {
      this.page = 1;
      this.hasMore = true;
      // this.loadJobList();
	  this.getJobList()
    },
    
    // 切换分类
    changeCategory(category) {
      this.currentCategory = category;
	  this.jobType = category.id
	  console.log('ssss1111',category.id)
	  this.getJobList()
      this.page = 1;
      this.hasMore = true;
      this.loadJobList();
    },
    
    // 切换排序
    changeSort(type) {
      if (type === this.sortType) {
        if (type === 'time') {
          this.timeSortOrder = this.timeSortOrder === 'asc' ? 'desc' : 'asc';
        } else if (type === 'salary') {
          this.salarySortOrder = this.salarySortOrder === 'asc' ? 'desc' : 'asc';
        }
      } else {
        this.sortType = type;
      }
      
      this.page = 1;
      this.hasMore = true;
      this.getJobList();
    },
    
    // 跳转到详情页
    navigateToDetail(id) {
      uni.navigateTo({
        url: `/pages/job/detail?id=${id}`
      });
    },
    
    // 跳转到发布页
    navigateToPublish() {
      uni.navigateTo({
        url: '/pages/job/publish'
      });
    }
  }
}
</script>

<style lang="scss" scoped>
.job-list-container {
  padding-bottom: 100rpx;
  
  .search-bar {
    padding: 20rpx 30rpx;
    background-color: #fff;
  }
  
  .category-scroll {
    white-space: nowrap;
    padding: 20rpx 30rpx;
    background-color: #fff;
    border-bottom: 1rpx solid #f0f0f0;
    
    .category-item {
      display: inline-block;
      margin-right: 40rpx;
      padding: 10rpx 20rpx;
      font-size: 28rpx;
      color: #666;
      border-radius: 30rpx;
      
      &.active {
        background-color: #07c160;
        color: #fff;
      }
      
      &:last-child {
        margin-right: 0;
      }
    }
  }
  
  .sort-options {
    display: flex;
    padding: 20rpx 30rpx;
    background-color: #fff;
    border-bottom: 1rpx solid #f0f0f0;
    
    .sort-item {
      display: flex;
      align-items: center;
      margin-right: 40rpx;
      font-size: 28rpx;
      color: #999;
      
      &.active {
        color: #07c160;
      }
      
      &:last-child {
        margin-right: 0;
      }
    }
  }
  
  .job-list {
    padding: 0 30rpx;
    
    .job-item {
      position: relative;
      margin-top: 30rpx;
      padding: 30rpx;
      background-color: #fff;
      border-radius: 12rpx;
      box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.05);
      
      .job-header {
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin-bottom: 20rpx;
        
        .job-title {
          font-size: 32rpx;
          font-weight: bold;
          color: #333;
          flex: 1;
          overflow: hidden;
          text-overflow: ellipsis;
          white-space: nowrap;
        }
        
        .job-salary {
          font-size: 32rpx;
          color: #ff5a5f;
          margin-left: 20rpx;
        }
      }
      
      .job-info {
        display: flex;
        flex-wrap: wrap;
        margin-bottom: 30rpx;
        
        .info-item {
          display: flex;
          align-items: center;
          margin-right: 30rpx;
          margin-bottom: 10rpx;
          font-size: 26rpx;
          color: #666;
          
          text {
            margin-left: 8rpx;
          }
        }
      }
      
      .job-footer {
        display: flex;
        justify-content: space-between;
        align-items: center;
        padding-top: 20rpx;
        border-top: 1rpx solid #f0f0f0;
        
        .company-info {
          display: flex;
          align-items: center;
          
          .company-logo {
            width: 50rpx;
            height: 50rpx;
            border-radius: 50%;
            margin-right: 15rpx;
          }
          
          .company-name {
            font-size: 26rpx;
            color: #666;
          }
        }
        
        .publish-time {
          font-size: 24rpx;
          color: #999;
        }
      }
      
      .job-tags {
        position: absolute;
        top: 30rpx;
        right: 30rpx;
        display: flex;
        
        .tag {
          margin-left: 10rpx;
          padding: 4rpx 12rpx;
          font-size: 22rpx;
          border-radius: 6rpx;
          
          &:nth-child(1) {
            background-color: #e6f7ff;
            color: #1890ff;
            border: 1rpx solid #91d5ff;
          }
          
          &:nth-child(2) {
            background-color: #fff7e6;
            color: #fa8c16;
            border: 1rpx solid #ffd591;
          }
          
          &:nth-child(3) {
            background-color: #f6ffed;
            color: #52c41a;
            border: 1rpx solid #b7eb8f;
          }
        }
      }
    }
    
    .load-more, .no-more {
      text-align: center;
      padding: 30rpx 0;
      font-size: 26rpx;
      color: #999;
    }
  }
  
  .publish-fab {
    position: fixed;
    right: 40rpx;
    bottom: 120rpx;
    display: flex;
    align-items: center;
    justify-content: center;
    width: 140rpx;
    height: 140rpx;
    background-color: #07c160;
    border-radius: 50%;
    box-shadow: 0 8rpx 20rpx rgba(7, 193, 96, 0.3);
    color: #fff;
    flex-direction: column;
    
    text {
      font-size: 24rpx;
      margin-top: 8rpx;
    }
  }
}
</style>